<?php

namespace app\common\model\auth;

use app\common\model\BaseModel;
use helper\Tree;


class RuleModel extends BaseModel
{
    protected $table = 'auth_rule';

    /**
     * 获取指定模块权限列表
     * @param $module
     * @param bool $refresh
     * @return array|mixed|object|\think\App
     * @throws \Exception
     */
    public function getAuthListByModule($module, $refresh = false)
    {
        $cacheKey = "auth_rule_{$module}";
        if (cache("?{$cacheKey}") && $refresh == false) return cache($cacheKey);
        $list = $this->where('module', $module)->order("show_order asc")->select()->toArray();
        $treeList = Tree::tree($list, 'title');
        cache($cacheKey, $treeList);
        return $treeList;
    }

    /**
     * 检测规则名唯一
     * @param $name
     * @param $module
     * @throws \Exception
     */
    public function checkName($name, $module)
    {
        $info = $this->where('name', $name)->where('module', $module)->find();
        if ($info) exception('该规则已存在');
    }

    /**
     * 拷贝树型数组
     * @param $from
     * @param $to
     * @return bool
     * @throws \Exception
     */
    public function copy($from, $to)
    {
        if ($this->where('module', $to)->find()) exception('对应模块已存在数据，不允许拷贝');
        //先全部拷贝
        $oldList = $this->withoutField('id,module')->field("'{$to}' as module")->where('module', $from)->select()->toArray();
        $this->saveAll($oldList);
        //修改对应pid值
        $oldPids = $this->where('module', $from)->where('pid', '>', 0)->column('pid', 'name');
        $oldIds = $this->where('module', $from)->column('name', 'id');
        $newList = $this->where('module', $to)->column('id,pid,name', 'name');
        $dataList = [];
        foreach ($newList as $v) {
            if ($v['pid'] == 0) continue;
            $newPid = $newList[$oldIds[$oldPids[$v['name']]]]['id'];
            $dataList[] = ['id' => $v['id'], 'pid' => $newPid];
        }
        $this->saveAll($dataList);
        return true;
    }

    /**
     * 添加规则
     * @param $data
     * @return RuleModel|\think\Model
     * @throws \Exception
     */
    public function add($data)
    {
        if (!isset($data['module'])) exception('请指定用户组模块');
        $this->checkName($data['name'], $data['module']);
        $info = self::create($data);
        $this->getAuthListByModule($info['module'], true);
        return $info;
    }

    /**
     * 修改规则
     * @param $data
     * @return RuleModel
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('id', $data['id'])->find();
        if ($data['name'] !== $info['name']) $this->checkName($data['name'], $info['module']);
        $data['module'] = $info['module'];
        $info = self::update($data);
        $this->getAuthListByModule($info['module'], true);
        return $info;
    }

    /**
     * 删除规则
     * @param $id
     * @throws \Exception
     */
    public function del($id)
    {
        if ($this->where('pid', $id)->find()) exception('存在下级，不允许删除');
        $module = $this->where('id', $id)->value('module');
        //去除对应分组表权限
        $exp = "TRIM(BOTH ',' FROM replace(concat(',',`rules`,','), ',{$id},', ','))";
        GroupModel::where('module', $module)->exp('rules', $exp)->update();
        $this->where('id', $id)->delete();
        $this->getAuthListByModule($module, true);
    }

}